package org.example.module_login.utlis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Arrays;
import java.util.Optional;

/**
 * 拦截器
 *
 * @author HAJ
 * @since 2025-03-03 15:17:42
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    /**
     * 拦截器（ 处理请求前 ） 业务逻辑
     * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = Optional.ofNullable(request.getCookies()) // 处理 request.getCookies() 为 null 的情况
                .map(cookies -> Arrays.stream(cookies)
                        .filter(cookie -> "Authorization".equals(cookie.getName()))
                        .findFirst()
                        .map(cookie -> cookie.getValue())
                        .orElse(null))
                .orElse(null);
        if (token != null) {
            return JWTToken.verifyToken(token);
        }
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
}
